import axios from 'axios';
import StorageUtil from '../utils/StorageUtil';

const instance = axios.create({
  baseURL: 'http://42.51.37.194/',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 20000,
});

instance.interceptors.request.use(
  async config => {
    const token = await StorageUtil.get('userToken');
    config.headers.Authorization = token ? 'Bearer ' + token : 'Bearer ';
    return config;
  },
  err => {
    return Promise.reject(err);
  },
);

instance.interceptors.response.use(
  res => {
    //在这里加入拦截代码
    const data = res.data;
    return data;
  },
  err => {
    return Promise.reject(err);
  },
);

function request(url, config = {method: '', params: {}, data: {}}) {
  return new Promise((resolve, reject) => {
    config.url = url;
    instance
      .request(config)
      .then(data => {
        return resolve(data);
      })
      .catch(err => {
        return reject(err);
      });
  });
}

function get(url, data = {}, config = {}) {
  config.params = data;
  return request(url, config);
}

function post(url, data = {}, config = {}) {
  config.data = data;
  config.method = 'post';
  return request(url, config);
}

export default {get, post, request};
